package thread;

import java.util.Random;

/**
 * @author Han
 * 多线程中每个线程自己的变量维护
 */
public class ThreadLocalDemo {
	private static final ThreadLocal<String> context = new ThreadLocal<String>();
	
	private static String contextStr = "";
	
	public static String get(){
		System.out.println(context);
		return context.get();
	}
	public static void set(String value){
		context.set(value);
	}
	public static String getStr(){
		return contextStr;
	}
	public static void setStr(String str){
		contextStr = str;
	}
	
	public class MyThread extends Thread{
		@Override
		public void run() {
			int i = new Random().nextInt(10);
			String str = Thread.currentThread().getId()+","+i;
			ThreadLocalDemo.set(str);
			ThreadLocalDemo.setStr(str);
			System.out.println("threadlocal的值"+str);
			System.out.println("string的值"+str);
			try {
				Thread.currentThread().sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("threadlocal的值"+ThreadLocalDemo.get());
			System.out.println("String的值"+ThreadLocalDemo.getStr());
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		//运行以下代码可以看出，两个线程，持有的threadlocal没有因为另一个改变了值而发生改变
		Thread t1 = new ThreadLocalDemo().new MyThread();
		Thread t2 = new ThreadLocalDemo().new MyThread();
		t1.start();
		t2.start();
	}
}
